﻿$ErrorState = 2
$ErrorMessage = ""
$Trace = ""
$Value = ""
$Error.Clear()

$virstoNamespace = "root\virtualization\storage"
$virstoServerClass = "Virsto_VSServer"
$snapName = '%SNAPNAME%'
$diskId = "%DISKID%"
$snapId = ""
$snapDescription = "%DISCRIPTION%"

try {

  $Trace += 'Connecting to Virsto...  \n'

  $virstoServer = Get-WmiObject -Namespace $virstoNamespace -Class $virstoServerClass
  $vdisk1 = gwmi -query "select * from Virsto_VSVDisk where Id=$diskId" -namespace "root\virtualization\storage"

  $snapshot = gwmi -query "select * from Virsto_VSSnapshot where Name='$snapName'" -namespace "root\virtualization\storage"
  if ($snapshot -eq $null) {
    
    $Trace += 'Creating Virsto Disk...  \n'
    $result = $virstoServer.CreateSnapshot($snapName, $vdisk1.Path.RelativePath, $snapDescription, 0)

	if ($result -eq $null)
	{
		$ErrorState = 1
		$Trace += 'Virsto SnapShot not created...  \n'
	}
	else
	{
		$ErrorState = 3
		$Trace += 'Virsto SnapShot creation successfull startet...  \n'
		$snapId = $result.Snapshot.Split("=")[1]
		$snapId = $snapId -replace '"(.*?)"','$1'
		$Trace += 'Virsto SnapShot Id is: ' + $snapId + ' \n'
	    $snapshot = gwmi -query "select * from Virsto_VSSnapshot where Id = $snapId"  -namespace "root\virtualization\storage"
	    while ($snapshot.Status -ne "OK") {
	       $status = $snapshot.Status
	       $Trace += 'Waiting for SnapShot to complete, Status: ' + $status + ' \n'
	       Start-Sleep -Seconds 2
	       $snapshot = gwmi -query "select * from Virsto_VSSnapshot where Id = $snapId"  -namespace "root\virtualization\storage"
	    }
		$Trace += 'Virsto Snapshot successfull created...  \n'
		$ErrorState = 0
	}
  }
  else
  {
	 $ErrorState = 0
	 $Trace += 'Virsto SnapShot already created...  \n'
     $snapId = $snapshot.Id
     $Trace += 'Virsto SnapShot Id is: ' + $snapId + ' \n'
  }

}
catch
{
  $ErrorState = 2
  $ErrorMessage = $error[0].Exception.ToString()
}
Finally
{
  $Trace += 'ErrorState:  ' + $ErrorState + ' \n'
  $Trace += 'ErrorMessage: ' + $ErrorMessage + ' \n'
  $Trace += 'SnapId: ' + $snapId + ' \n'
}

$Results = @($ErrorState, $ErrorMessage, $Trace, $snapId) 
Return $Results


